import { message } from 'antd';
import axios from 'axios';
import { getToken, removeToken } from './storage';

import history from './history';

export const baseURL = 'http://geek.itheima.net';
const instance = axios.create({
  baseURL: baseURL,
  timeout: 5000,
});

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    if (getToken()) {
      config.headers.Authorization = `Bearer ${getToken()}`;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 💥小小的改造，多解构了一个data，再返回
    return response.data;
  },
  function (error) {
    console.dir(error);
    if (error.response.status === 401) {
      // token 过期
      removeToken();
      // 重定向到登录页
      // window.location.href = '/login';
      console.log(history);
      history.push('/login');
      // 提示用户
      message.warning(error.response.data.message);
    }
    return Promise.reject(error);
  }
);

export default instance;
